package com.bluedon.ism.commons.util;

import org.apache.commons.io.FileUtils;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

/**
 * 文件处理工具 extends org.apache.commons.io.FileUtils
 * 
 */
public class FileUtil extends FileUtils {
	
	private static Logger logger = LoggerFactory.getLogger(FileUtil.class);

	public static void copyFileQuietly(File srcFile, File destFile) {
		try {
			copyFile(srcFile, destFile);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("copy文件出错: " + e);
		}
	}

	/**
	 * 备份已有文件
	 * 
	 * @param file
	 */
	public static void backupExistFile(final File file) {
		if (file.exists()) {
			File parent = file.getParentFile();
			File[] children = parent.listFiles(new FilenameFilter() {

				@Override
				public boolean accept(File dir, String name) {
					return name.contains(file.getName());
				}
			});
			Arrays.sort(children);
			String lastCode = children[children.length - 1].getName().replace(
					file.getName(), "");
			if (lastCode.equals("") || !StringUtil.isNumeric(lastCode)) {
				lastCode = ".1";
			} else {
				int code = Integer.parseInt(lastCode.substring(1));
				code++;
				lastCode = "." + code;
			}
			File destFile = new File(file.getParentFile(), file.getName()
					+ lastCode);
			file.renameTo(destFile);
		}
	}
	
	/**
	 * 打包
	 * @param srcPath 源路径
	 * @param destPath 目录路径
	 * @param includesRegxStr 打包要包含要文件 比如**\/*.java)
	 * @param excludesRegxstr 打包排附除的文件
	 */
	public static void compressZip(String srcPath,String destPath,String includesRegxStr,String excludesRegxstr) {
		
		File srcdir = new File(srcPath);
		if (!srcdir.exists())
			throw new RuntimeException(srcPath + "不存在！");
		File zipFile = new File(destPath);
		File parent = zipFile.getParentFile();
		if(parent.exists()){
			parent.mkdir();
		}
		Project prj = new Project();
		Zip zip = new Zip();
		zip.setProject(prj);
		zip.setDestFile(zipFile);
		zip.setCompress(false);//不压缩文件，只打包存储
		FileSet fileSet = new FileSet();
		fileSet.setProject(prj);
		fileSet.setDir(srcdir);
		if(includesRegxStr != null && !"".equals(includesRegxStr))
			fileSet.setIncludes(includesRegxStr); 
		if(excludesRegxstr != null && !"".equals(excludesRegxstr))
			fileSet.setExcludes(excludesRegxstr); 
		zip.addFileset(fileSet);
		zip.execute();
		//删除这个目录下的bcp文件
		//delFiles(srcPath,new String[]{"bcp"});
		
	}

	/**
	 * 删除指定目录下的指定文件类型的文件，不会删除子目录下的文件
	 * @param path
	 * @param filetype
	 * @return
	 */
	public static boolean delFiles(String path, String[] filetype){
		File file = new File(path);
		try{
		if (file.isDirectory() && file.exists()){
			Collection<File> flist = FileUtils.listFiles(file, filetype, false);
			Iterator<File> it = flist.iterator();
			while (it.hasNext()){
				File delfile = it.next();
				delfile.delete();
				logger.debug("FileUtil: delete file : " + delfile.getAbsolutePath());
			}
			return true;
		}
		}catch (Exception e){
			e.printStackTrace();
			return false;
		}
		return false;
	}
	
	/**
	 * 根据传入的输入流和文件全路径生成文件
	 * @param fullFilePath
	 * @param is
	 */
	public static void generateFile(String fullFilePath, InputStream is){
		byte[] Buffer = new byte[4096];
		OutputStream writer = null;
		try {
			File file = new File(fullFilePath);
			writer = new BufferedOutputStream(new FileOutputStream(file));
			int size = 0;
			while((size = is.read(Buffer)) != -1){
				writer.write(Buffer, 0, size);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if (writer != null){
					writer.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (NullPointerException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 获取指定目录下zip文件路径
	 * @path 目录路径
	 * @return
	 */
	public static String getZipFile(File file){
		String filepath = null;
		if (file.exists() && file.isDirectory()){
			Collection<File> flist = FileUtils.listFiles(file, new String[]{"zip"}, false);
			Iterator<File> it = flist.iterator();
			while (it.hasNext()){
				File f = it.next();
				filepath = f.getAbsolutePath();
				//找到一个文件后推出循环
				break;
			}
		}
		return filepath;
	}
	
    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful.
     *                 If a deletion fails, the method stops attempting to
     *                 delete and returns "false".
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }
	
	
	public static void main(String[] args) {
		compressZip("D:\\", "D:\\xslbcp.zip", "/*.xls", "");
		//delFiles("D:\\", new String[] {"txt","xls","xlsx","db"});
	}

}
